﻿/*****************************************************************//**
 * \file   check.c
 * \brief  一些校验函数
 * 
 * \author CaiYunWei
 * \date   September 2024
 *********************************************************************/
#include "check.h"

/*
* @brief 调试用二进制打印一个字节
*/
void binPrintf(uint8_t binData)
{
    for (int i = 0; i < 8; i++)
    {
        if (binData & (0x80 >> i))
            putchar('1');
        else
            putchar('0');
    }
}

void additionChecksum_8BIT(const void* pStart, size_t count, void* pResult)
{
	uint8_t sum = 0X00;
	uint8_t* pData = (uint8_t*)pStart;
	for (size_t i = 0; i < count; i++)
	{
		sum += pData[i];
	}

	*((uint8_t*)pResult) = sum;
}

#define POLY_8 0x07


void left_and_supply(uint8_t* D_now, uint8_t D_next, int i)
{
    (*D_now) <<= 1;
    if (D_next & (0x80 >> i))
        (*D_now) |= 0x01;    
}



void bigCRC_8(const void* pStart, size_t count, void* pResult)
{
    uint8_t crc = 0x00;                   //初始值
    uint8_t* p = (uint8_t*)pStart;
    uint8_t* pEnd = (uint8_t*)pStart + count - 1;
    int i;
    for (; p<=pEnd; p++)
    {        
        crc ^= *p;                    //与crc初始值异或
        for (i = 0; i < 8; i++)       //循环8位 
        {
            if (crc & 0x80)           //左移移出的位为1，左移后与多项式异或
            {
                crc <<= 1;
                crc ^= POLY_8;
            }
            else                      //否则直接左移
            {
                crc <<= 1;
            }
        }

    }

    *((uint8_t*)pResult) = crc;
}



/**
 * @brief 
 * @param pStart 
 * @param count 
 * @param pResult 
*/
void CRC_8(const void* pStart, size_t count, void* pResult)
{
    uint8_t* pEnd = (uint8_t*)pStart + count - 1;
    uint8_t* p = (uint8_t*)pStart;
    uint8_t crc = *p; 
    int i;

    for (; p < pEnd; )
    {
        p++;
        for (i = 0; i < 8; i++)                //循环8位 
        {
            if (crc & 0x80)//最高位为1，应当再次左移后与多项式异或
            {
                crc <<= 1;
                if (*p & (0x80 >> i))
                    crc |= 0x01;
                crc ^= POLY_8;
            }
            else
            {
                crc <<= 1;
                if (*p & (0x80 >> i))
                    crc |= 0x01;
            }
        }
    }

    uint8_t tem = 0x00;//补8个0
    p = &tem;
    for (i = 0; i < 8; i++)                //循环8位 
    {
        if (crc & 0x80)//最高位为1，应当再次左移后与多项式异或
        {
            crc <<= 1;
            if (*p & (0x80 >> i))
                crc |= 0x01;
            crc ^= POLY_8;
        }
        else                               //否则直接左移
        {
            crc <<= 1;
            if (*p & (0x80 >> i))
                crc |= 0x01;
        }
    }
    *((uint8_t*)pResult) = crc;
}
